<template>
  <div class="wrapper-add-edit">
    <div class="wrapper-form">
      <el-form ref="refForm" :model="formData" label-width="100px">
        <el-form-item label="任务类别">
          <el-tree-select
            ref="refTSCategory"
            v-model="formData.idCategory"
            :data="dataTSCategory"
            :props="{ value: 'id', label: 'label' }"
            :render-after-expand="false"
            :current-node-key="0"
            :default-expanded-keys="selectedKeys"
            value-key="id"
            placeholder="选择任务所属类别"
            check-strictly
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="任务级别">
          <el-radio-group ref="refLevel" v-model="formData.level">
            <el-radio value="国家级">国家级</el-radio>
            <el-radio value="省级">省级</el-radio>
            <el-radio value="市级">市级</el-radio>
            <el-radio value="区级">区级</el-radio>
            <el-radio value="本单位">本单位</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="任务标题">
          <el-input ref="refTitle" v-model="formData.article.title" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="任务目标">
          <el-input v-model="formData.introGoal" :rows="6" type="textarea" maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="任务简介">
          <el-input v-model="formData.article.intro" :rows="6" type="textarea" maxlength="2000" show-word-limit />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" :rows="6" type="textarea" maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="任务起止时间">
          <el-col :span="8">
            <el-date-picker
              ref="refStartEndDate"
              v-model="dtStartEnd"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcutDateRange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onUpdate()">保存提交</el-button>
          <el-button @click="onBack2List()">取消并返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { obj2Str, str2Str } from '@/utils/datetime'
import { AryToTree } from '@/utils/array'
import { toastSuccess, toastError } from '@/utils/toast'
import { getLStorageObj, getSStorageObj } from '@/utils/web-storage'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'TaskEditView',
  setup() {
    const formData = ref({
      article: {
        id: 0,
        idCategory: 3,
        idUnit: 106,
        idDepartment: 106,
        symbolShow: '',
        source: '',
        status: '0',
        author: '',
        idEditor: 0,
        idChecker: 0,
        idSigner: 0,
        tag: '',
        title: '',
        titleHead: '',
        titleSub: '',
        titleShort: '',
        // 标题图不仅仅有图像的 url ，还有 uuid，因此这里存的是一个对象
        urlTitlePic: '',
        urlTitleVideo: '',
        urlJump: '',
        content: '',
        intro: '',
        dtCreate: obj2Str(new Date()),
        dtPublish: obj2Str(new Date()),
        flagDeleted: 0,
        weight: 1,
        click: 0,
      },
      idParent: 0,
      depth: 0,
      idCategory: 3,
      level: '',
      idOperator: 0,
      idChecker: 0,
      dtStart: '',
      dtEnd: '',
      introGoal: '',
      introFinished: '',
      remark: '',
      status: '',
      flagEnabled: 1,
      flagFinished: 0,
      dtCreate: obj2Str(new Date()),
      weight: 0,
    })
    const dataTSCategory = ref([])
    const selectedKeys = ref([])
    const dtStartEnd = ref([])
    const refForm = ref(null)
    const refTitle = ref(null)
    const refTSCategory = ref(null)
    const refLevel = ref(null)
    const refStartEndDate = ref(null)
    const shortcutDateRange = [
      {
        text: '一周',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
          return [start, end]
        },
      },
      {
        text: '二周',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 14)
          return [start, end]
        },
      },
      {
        text: '一个月',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
          return [start, end]
        },
      },
      {
        text: '三个月',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
      {
        text: '半年',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 180)
          return [start, end]
        },
      },
      {
        text: '一年',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 365)
          return [start, end]
        },
      },
      {
        text: '长期',
        value: () => {
          const start = new Date()
          const end = new Date()
          end.setTime(start.getTime() + 3600 * 1000 * 24 * 3650)
          return [start, end]
        },
      },
    ]

    const onBack2List = () => {
      router.push({ path: 'list-page' })
    }

    // 得到从list放在query里传过来的的详细资料
    const getQuery = () => {
      const task = getSStorageObj('ParamData')
      if (!task) onBack2List()
      formData.value = task
      // 设置下拉菜单点击时的展开状态
      selectedKeys.value.push(3)
      selectedKeys.value.push(task.idCategory)
      dtStartEnd.value.push(formData.value.dtStart)
      dtStartEnd.value.push(formData.value.dtEnd)
      console.log('dtStartEnd.value:', dtStartEnd.value)
    }
    // 得到所有任务类别
    const listCategory = () => {
      dataTSCategory.value = AryToTree(getLStorageObj('AllCategory'), 3)
    }

    const listAllParentId = () => {
      store
        .dispatch('sys_category/listAllParentId', 213)
        .then((response) => {
          console.log('所有上级id为：', response)
        })
        .catch((error) => {
          console.log('得到所有上级id出现错误：', error)
        })
    }
    // 验证表单
    const validForm = () => {
      // 验证标题
      if (formData.value.article.title === '') {
        toastError('任务标题不能为空！')
        refTitle.value.focus()
        return false
      }
      // 验证类别
      if (formData.value.idCategory === 3) {
        toastError('请选择任务类别！')
        refTSCategory.value.focus()
        return false
      }
      // 验证级别
      if (formData.value.level === '') {
        toastError('请选择任务级别！')
        refLevel.value.focus()
        return false
      }
      // 验证起止时间
      if (JSON.stringify(dtStartEnd.value) === JSON.stringify([])) {
        toastError('请选择任务起止时间！')
        refStartEndDate.value.focus()
        return false
      }
      return true
    }

    const onUpdate = () => {
      // 验证表单
      if (!validForm()) {
        return
      }
      console.log('formData2.value:', formData.value)
      console.log('dtStartEnd.value:', dtStartEnd.value)
      formData.value.article.idCategory = formData.value.idCategory
      formData.value.dtStart = str2Str(dtStartEnd.value[0], 'yyyy-MM-dd HH:mm:ss', '{y}-{m}-{d}') + ' 00:00:00'
      formData.value.dtEnd = str2Str(dtStartEnd.value[1], 'yyyy-MM-dd HH:mm:ss', '{y}-{m}-{d}') + ' 00:00:00'
      console.log('formData.value.dtStart:', formData.value.dtStart)
      console.log('formData.value.dtEnd:', formData.value.dtEnd)
      store
        .dispatch('task/modifyAll', formData.value)
        .then(() => {
          toastSuccess('修改成功！')
          router.push({ path: 'list-page' })
        })
        .catch((error) => {
          toastError(error)
        })
    }

    onMounted(() => {
      listCategory()
      getQuery()
      listAllParentId()
    })

    return {
      formData,
      dataTSCategory,
      selectedKeys,
      dtStartEnd,
      refForm,
      refTitle,
      refTSCategory,
      refLevel,
      refStartEndDate,
      shortcutDateRange,

      onBack2List,
      getQuery,
      listCategory,
      listAllParentId,
      validForm,
      onUpdate,
    }
  },
})
</script>

<style lang="scss" scoped></style>
